/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatclient;

import java.awt.event.KeyEvent;
import javax.swing.DefaultListModel;
import javax.swing.text.DefaultCaret;


/**
 *
 * @author freeman
 */
public class ClientGUI extends javax.swing.JFrame {
    
    
    private ClientThread thread = null;
    private boolean isConnected = false;
    private int curGlobalUsers = 0;
    

    /**
     * Creates new form ClientGUI
     */
    public ClientGUI() {
        initComponents();
        DefaultCaret caret = (DefaultCaret)userMessageView.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }
    
    /*
     * Puts a message in the view area for the client
     * 
     * @param message: The message to put.
     */
    public synchronized void putMessage(String message) {
        userMessageView.setText(userMessageView.getText() + message + "\n");
    }
    
    
    /*
     * Is called from ClientThread to handle whether or not
     * the clientthread was able to connect to the server.
     * 
     * This method takes care of some gui esoterics that should change
     * when the client has connected (or not)
     * 
     * @param isConnected: Whether or not the client is connected to 
     *  a server.
     */
    public synchronized void notifyConnectState(boolean isConnected) {
        if ( isConnected ) {
            this.isConnected = true;
            connectButton.setText("Disconnect");
            sendButton.setEnabled(true);
            
            DefaultListModel model = new DefaultListModel();
            userList.setModel(model);
        } else {
            this.isConnected = false;
            connectButton.setText("Connect");
            sendButton.setEnabled(false);
            
            DefaultListModel model = new DefaultListModel();
            model.addElement("<not connected>");
            userList.setModel(model);
        }
    }
    
    /*
     * Handles the updating of the userlist based on the master
     * user list send by the server.
     */
    public synchronized void updateUserList(String userNameList) {
        if ( !userNameList.contains(":")) {
            System.err.println("ClientGUI: Username list is not "
                    + "properly formatted: [" + userNameList + "] Not updating.");
            return;
        }
        
        /*create a new model and add the usernames to it*/
        DefaultListModel model = new DefaultListModel();
        
        String[] usernames = userNameList.split(":");
        for ( int i = 0; i < usernames.length; i++ ) {
            model.addElement(usernames[i]);
        }
        
        /*apply the new model*/
        userList.setModel(model);
        
        /*get total # users*/
        curGlobalUsers = usernames.length - 1;
        onlineUsersLabel.setText("Online Users: " + curGlobalUsers);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        addressField = new javax.swing.JTextField();
        connectButton = new javax.swing.JButton();
        portField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        userMessageView = new javax.swing.JEditorPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        userMessageArea = new javax.swing.JTextArea();
        sendButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        userList = new javax.swing.JList();
        onlineUsersLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setForeground(java.awt.Color.gray);
        setPreferredSize(new java.awt.Dimension(932, 383));

        jPanel1.setBackground(new java.awt.Color(197, 197, 197));

        jLabel1.setText("Username:");

        jLabel2.setText("Address:");

        usernameField.setText("Sam Smith");
        usernameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameFieldActionPerformed(evt);
            }
        });

        addressField.setText("localhost");

        connectButton.setText("Connect");
        connectButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                connectButtonStateChanged(evt);
            }
        });
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        portField.setText("45537");
        portField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                portFieldActionPerformed(evt);
            }
        });

        jLabel7.setText("Port:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(connectButton)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(portField)
                            .addComponent(usernameField, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                            .addComponent(addressField))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(addressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(5, 5, 5)
                .addComponent(connectButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        userMessageView.setEditable(false);
        userMessageView.setAutoscrolls(true);
        userMessageView.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                userMessageViewCaretUpdate(evt);
            }
        });
        jScrollPane1.setViewportView(userMessageView);

        userMessageArea.setColumns(20);
        userMessageArea.setRows(5);
        userMessageArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                userMessageAreaKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                userMessageAreaKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                userMessageAreaKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(userMessageArea);

        sendButton.setText("Send");
        sendButton.setEnabled(false);
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        userList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "<not connected>" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(userList);

        onlineUsersLabel.setText("Online Users: "+curGlobalUsers);

        jLabel4.setText("Messages");

        jLabel5.setText("Login Information");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(sendButton)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(jScrollPane2))
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(onlineUsersLabel)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(onlineUsersLabel)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                                .addGap(2, 2, 2)
                                .addComponent(jLabel6)
                                .addGap(1, 1, 1)
                                .addComponent(jScrollPane2))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed

        if ( isConnected ) {
            thread.disconnect();
            curGlobalUsers = 0;
            onlineUsersLabel.setText( "Online Users: " + curGlobalUsers);
            return;
        }
        thread = new ClientThread(this, usernameField.getText(), addressField.getText(), portField.getText());
        thread.start();
    }//GEN-LAST:event_connectButtonActionPerformed

    
    private void usernameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameFieldActionPerformed
        //maybe add some validation?
    }//GEN-LAST:event_usernameFieldActionPerformed

    private void userMessageAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userMessageAreaKeyPressed
        
    }//GEN-LAST:event_userMessageAreaKeyPressed

    private void connectButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_connectButtonStateChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_connectButtonStateChanged

    private void portFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_portFieldActionPerformed

    private void userMessageAreaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userMessageAreaKeyReleased
        if ( evt.getKeyCode() == KeyEvent.VK_ENTER ) {
            if ( !this.isConnected ) {
                putMessage("Could not send message, not connected.");
                userMessageArea.setText("");
                userMessageArea.setCaretPosition(0);
                return;
            }
            thread.sendPubChatMessage(userMessageArea.getText());
            userMessageArea.setText("");
            userMessageArea.setCaretPosition(0);
        }
    }//GEN-LAST:event_userMessageAreaKeyReleased

    private void userMessageAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userMessageAreaKeyTyped
        
    }//GEN-LAST:event_userMessageAreaKeyTyped

    private void userMessageViewCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_userMessageViewCaretUpdate
            
        
    }//GEN-LAST:event_userMessageViewCaretUpdate

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
            if ( !this.isConnected ) {
                putMessage("Cannot send message, not connected.");
                userMessageArea.setText("");
                userMessageArea.setCaretPosition(0);
                return;
            }
            thread.sendPubChatMessage(userMessageArea.getText());
            userMessageArea.setText("");
            userMessageArea.setCaretPosition(0);
        
    }//GEN-LAST:event_sendButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addressField;
    private javax.swing.JButton connectButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel onlineUsersLabel;
    private javax.swing.JTextField portField;
    private javax.swing.JButton sendButton;
    private javax.swing.JList userList;
    private javax.swing.JTextArea userMessageArea;
    private javax.swing.JEditorPane userMessageView;
    private javax.swing.JTextField usernameField;
    // End of variables declaration//GEN-END:variables
}
